package pers.bc.utils.pub;

import java.io.File;
import java.io.InputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.InputSource;

/**
 * @version 1.0<br>
 * @qualiFild nc.pub.itf.tools.pub.XMLUtils.java<br>
 * @author：licheng<br>
 * @date Created on 2019-8-12<br>
 */
public final class XmlUtil {
	private static final SAXTransformerFactory saxFactory = (SAXTransformerFactory) SAXTransformerFactory
			.newInstance();

	private static TransformerFactory transformerFactory;

	public XmlUtil() {
	}

	public static TransformerHandler createTransformerHandler()
			throws TransformerConfigurationException {
		return saxFactory.newTransformerHandler();
	}

	public static TransformerHandler createTransformerHandler(Templates template)
			throws TransformerConfigurationException {
		return saxFactory.newTransformerHandler(template);
	}

	public static Templates createTemplate(InputStream is)
			throws TransformerConfigurationException {
		return createTemplate(new StreamSource(is));
	}

	public static Templates createTemplate(File file)
			throws TransformerConfigurationException {
		return createTemplate(new StreamSource(file));
	}

	private static Templates createTemplate(StreamSource streamSource)
			throws TransformerConfigurationException {
		if (transformerFactory == null) {
			synchronized (XmlUtil.class) {
				if (transformerFactory == null) {
					transformerFactory = TransformerFactory.newInstance();
				}
			}
		}
		return transformerFactory.newTemplates(streamSource);
	}

	/*************************************************************
	 * <br>
	 * 
	 * 说明:是否是xml文档 <br>
	 * 
	 * @Description <br>
	 * @Date Created on 2020/9/29 15:13 <br>
	 * @Param [rtnMsg] <br>
	 * @return boolean <br>
	 * @Author LIBENCHENG
	 * @version 1.0 <br>
	 ************************************************************* <br>
	 */
	public static boolean isXmlDocument(String rtnMsg) {
		boolean flag = true;
		try {
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = documentBuilderFactory
					.newDocumentBuilder();
			builder.parse(new InputSource(new StringReader(rtnMsg)));
		} catch (Exception e) {
			flag = false;
		}

		return flag;
	}

}
